package org.dromara.third.auth.common.auth;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.BusinessServiceException;
import org.dromara.third.auth.beans.constans.Constants;
import org.dromara.third.auth.beans.constans.ExceptionEnum;
import org.dromara.third.auth.config.AuthConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;


/**
 * 权限验证过滤器（直接移植至业务模块）
 *
 * @author admin
 * @date 2020/7/13 15:04
 */
@Slf4j
@Component
@NoArgsConstructor
public class AuthBaseFilter implements HandlerInterceptor {

    @Autowired
    private AuthConfig authConfig;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("token");
        //头部信息不包含token，禁止请求接口
        if (StringUtils.isEmpty(token)) {
            log.info("header中token为空，用户验证失效，请重新获取token");
            throw new BusinessServiceException(ExceptionEnum.AuthException05.getCode(), ExceptionEnum.AuthException05.getMessage());
        }

        //解析token
        try {
            Claims claims = Jwts.parser().setSigningKey(authConfig.getPrivateKey()).parseClaimsJws(token).getBody();
            //校验通过，将用企业编码放到header中
            String orgCode = String.valueOf(claims.get(Constants.COMPANY_CODE));
            TokenThreadLocal.setThreadLocal(orgCode);
            request.setAttribute(Constants.COMPANY_CODE, claims.get(Constants.COMPANY_CODE));
        } catch (Exception e) {
            throw new BusinessServiceException(ExceptionEnum.AuthException04.getCode(), ExceptionEnum.AuthException04.getMessage());
        }
        return true;
    }
}
